package com.qinge.blog.service.impl;

import com.qinge.blog.dao.BlogRoleDao;
import com.qinge.blog.entity.BlogRole;
import com.qinge.blog.entity.BlogRoleExample;
import com.qinge.blog.entity.BlogUserRoleExample;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qinge.blog.dao.BlogUserRoleDao;
import com.qinge.blog.service.BlogUserRoleService;
import com.qinge.blog.entity.BlogUserRole;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author QDW
 * @date 2022-05-02 23:38:51
 * @description BlogUserRole service层实现类
 */
@Service
public class BlogUserRoleServiceImpl  implements BlogUserRoleService {

    @Resource
    BlogUserRoleDao userRoleDao;

    @Resource
    BlogRoleDao roleDao;

    @Override
    public List<String> findRolesByUserId(String userId) {
        BlogUserRoleExample example=new BlogUserRoleExample();
        BlogUserRoleExample.Criteria criteria=example.createCriteria();

        criteria.andUserIdEqualTo(userId);

        List<BlogUserRole> userRoles = userRoleDao.selectByExample(example);

        List<String> roleIds=userRoles.stream().map(BlogUserRole::getRoleId).collect(Collectors.toList());

        BlogRoleExample roleExample=new BlogRoleExample();
        BlogRoleExample.Criteria roleCriteria=roleExample.createCriteria();

        roleCriteria.andIdIn(roleIds);

        List<BlogRole> roles=roleDao.selectByExample(roleExample);

        return roles.stream().map(BlogRole::getRoleName).collect(Collectors.toList());
    }

    @Override
    public void add(List<String> userIds, List<String> roleIds) {
        List<BlogUserRole> list=new ArrayList<>(userIds.size()* roleIds.size());

        for(String userId:userIds){
            for (String roleId:roleIds){
                BlogUserRole userRole=new BlogUserRole();

                userRole.setUserId(userId);
                userRole.setRoleId(roleId);

                list.add(userRole);
            }
        }

        userRoleDao.batchInsert(list);
    }

    @Override
    public void removeByUserIds(List<String> userIds) {
        BlogUserRoleExample example=new BlogUserRoleExample();
        BlogUserRoleExample.Criteria criteria=example.createCriteria();

        criteria.andRoleIdIn(userIds);

        userRoleDao.deleteByExample(example);
    }

    @Override
    public void removeByRoleIds(List<String> roleIds) {
        BlogUserRoleExample example=new BlogUserRoleExample();
        BlogUserRoleExample.Criteria criteria=example.createCriteria();

        criteria.andRoleIdIn(roleIds);

        userRoleDao.deleteByExample(example);
    }

    @Override
    public void update(List<String> userIds, List<String> roleIds) {
        removeByUserIds(userIds);

        add(userIds,roleIds);
    }
}

